<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="需求id" prop="requireId">
        <el-input v-model="queryParams.requireId" placeholder="请输入需求id" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="用户姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入用户姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable @change="handleQuery"
          style="width: 200px;">
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="出生日期" prop="birthday">
        <el-date-picker clearable v-model="queryParams.birthday" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择出生日期">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="所属学院" prop="college">
        <el-input v-model="queryParams.college" placeholder="请输入所属学院" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所学专业" prop="major">
        <el-input v-model="queryParams.major" placeholder="请输入所学专业" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-input v-model="queryParams.grade" placeholder="请输入年级" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="审核状态" prop="approveStatus">
        <el-select v-model="queryParams.approveStatus" placeholder="请选择审核状态" clearable @change="handleQuery"
          style="width: 200px;">
          <el-option label="待审核" value="0" />
          <el-option label="已通过" value="1" />
          <el-option label="已拒绝" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['rms-bus:approve:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['rms-bus:approve:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['rms-bus:approve:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['rms-bus:approve:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="approveList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="申请id，主键" align="center" prop="signupId" />
                    <el-table-column label="需求id" align="center" prop="requireId" /> -->
      <el-table-column label="用户姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          {{ getGenderLabel(scope.row.gender) }}
        </template>
      </el-table-column>
      <el-table-column label="出生日期" align="center" prop="birthday" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属学院" align="center" prop="college" />
      <el-table-column label="所学专业" align="center" prop="major" />
      <el-table-column label="年级" align="center" prop="grade" />
      <el-table-column label="报名表附件" align="center" prop="fileUrl">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleViewLink(scope.row.fileUrl)">
            查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="approveStatus">
        <template #default="scope">
          <el-tag :type="getApproveStatusTagType(scope.row.approveStatus)">
            {{ getApproveStatusLabel(scope.row.approveStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="scope.row.approveStatus === 0" link type="primary" icon="Edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['signup:approve:edit']">审核</el-button>
          
          <!-- 添加查看详情按钮 -->
          <el-button link type="primary" icon="View" @click="handleViewDetail(scope.row)" 
            v-if="scope.row.approveStatus !== 0">查看审核信息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改企业审核对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="approveRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="申请人编号" prop="signupId">
            <el-input v-model="form.signupId" placeholder="请输入申请id" />
          </el-form-item> -->
        <!-- <el-form-item label="审核人" prop="approverId">
            <el-input v-model="form.approverId" placeholder="请输入审核人" />
          </el-form-item> -->
        <!-- <el-form-item label="审核时间" prop="approveTime">
            <el-date-picker clearable v-model="form.approveTime" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择审核时间">
            </el-date-picker>
          </el-form-item> -->
        <el-form-item label="审核状态" prop="approveStatus">
          <el-radio-group v-model="form.approveStatus">
            <el-radio v-for="item in approveStatusOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="审核意见" prop="approveReview" required>
          <el-input v-model="form.approveReview" type="textarea" :rows="4" :maxlength="200" show-word-limit
            placeholder="请输入审核意见" @keydown="handleKeydown" @input="handleInput" />
        </el-form-item>
        
      </el-form>
      <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
    </el-dialog>

    <el-dialog title="审核详情" v-model="detailOpen" width="500px" append-to-body>
      <el-form :model="detailForm" label-width="80px">
        <el-form-item label="用户姓名:">
          <span>{{ detailForm.name }}</span>
        </el-form-item>
        <el-form-item label="审核状态:">
          <el-tag :type="getApproveStatusTagType(detailForm.approveStatus)">
            {{ getApproveStatusLabel(detailForm.approveStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="审核意见:">
          <el-input 
            type="textarea" 
            :rows="4" 
            v-model="detailForm.approveReview" 
            readonly>
          </el-input>
        </el-form-item>
        <el-form-item label="审核时间:">
          <span>{{ parseTime(detailForm.approveTime, '{y}-{m}-{d}') }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Approve">
  import {
    listApprove,
    getApprove,
    delApprove,
    addApprove,
    updateApprove
  } from "@/api/signup/approve";
  const baseApi = import.meta.env.VITE_APP_BASE_API

  const {
    proxy
  } = getCurrentInstance();

  const approveList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      requireId: null, // 新增字段，用于查询
      gender: null,
      college: null,
      major: null,
      grade: null,
      approveStatus: null
    },
    rules: {
      approveReview: [{
        required: true,
        message: '审核意见不能为空',
        trigger: 'blur'
      }]
    }
  });


  const {
    queryParams,
    form,
    rules
  } = toRefs(data);


    // 添加详情相关变量
  const detailOpen = ref(false);
  const detailForm = ref({});

  // 查看详情按钮操作
  function handleViewDetail(row) {
    detailForm.value = { ...row };
    detailOpen.value = true;
  }

  /** 查询企业审核列表 */
  function getList() {
    loading.value = true;
    listApprove(queryParams.value).then(response => {
      approveList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 表单重置
  function reset() {
    form.value = {
      approveId: null,
      signupId: undefined, // 改为 undefined 而不是 null
      approverId: null,
      approveStatus: null,
      approveTime: null,
      approveReview: null
    };
    proxy.resetForm("approveRef");
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.approveId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加企业审核";
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    if (!row.signupId) {
      proxy.$modal.msgError("数据异常，缺少 signupId");
      return;
    }

    reset();

    getApprove(row.signupId).then(response => {
      form.value = {
        ...response.data
      }; // 深拷贝数据
      openDialog();
      title.value = "审核结果";
    }).catch(error => {
      console.error("请求失败：", error);
      proxy.$modal.msgError("获取数据失败");
    });
  }

  /** 提交按钮 */
  function submitForm() {
    // 审核意见非空校验
    if (!form.value.approveReview || !form.value.approveReview.trim()) {
      proxy.$modal.msgError("审核意见不能为空");
      return;
    }
    proxy.$refs["approveRef"].validate(valid => {
      if (valid) {
        if (form.value.signupId != null) {
          updateApprove(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addApprove(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _signupIds = row.signupId || ids.value;
    proxy.$modal.confirm('是否确认删除企业审核编号为"' + _signupIds + '"的数据项？').then(function() {
      return delApprove(_signupIds);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('signup/approve/export', {
      ...queryParams.value
    }, `approve_${new Date().getTime()}.xlsx`)
  }

  // 审核状态映射关系
  const approveStatusMap = {
    0: {
      label: '待审核',
      type: 'info'
    },
    1: {
      label: '已通过',
      type: 'success'
    },
    2: {
      label: '已拒绝',
      type: 'danger'
    }
  };

  // 获取标签显示文字
  function getApproveStatusLabel(value) {
    return approveStatusMap[value]?.label || '未知状态';
  }

  // 获取标签样式类型（用于 el-tag 的 type 属性）
  function getApproveStatusTagType(value) {
    return approveStatusMap[value]?.type || 'warning';
  }

  // 打开弹窗的方法
  function openDialog() {
    open.value = true;
    form.value.approveStatus = 1; // 注意：approveStatusOptions 的 value 是数字 1
  }

  const approveStatusOptions = [{
      label: '通过',
      value: 1
    },
    {
      label: '拒绝',
      value: 2
    }
  ];

  // 性别映射关系
  const genderMap = {
    1: '男',
    2: '女'
  };

  // 获取性别显示文字
  function getGenderLabel(value) {
    return genderMap[value] || '其他';
  }

  const handleViewLink = (url) => {
    console.log(url)
    if (!url) {
      ElMessage.warning('暂无链接信息');
      return;
    }

    // 拼接完整路径
    const fullPath = baseApi + `/profile/download?fullPath=${url}`;
    console.log(fullPath)
    // 创建 <a> 标签
    const link = document.createElement('a');
    link.href = fullPath;
    link.download = url.split('/').pop(); // 设置下载的文件名，也可以自定义
    link.target = '_blank'; // 新窗口打开（非必需）
    link.click(); // 触发点击
  };


  import {
    nextTick
  } from 'vue'

  /* 允许的最大行数 */
  const MAX_LINES = 4

  /* 通用的截断函数 */
  function truncateLines(text) {
    const lines = text.replace(/\n+$/, '').split('\n')
    if (lines.length <= MAX_LINES) return text
    return lines.slice(0, MAX_LINES).join('\n')
  }

  /* 1. 拦截键盘回车 */
  function handleKeydown(e) {
    // Enter 键
    if (e.key === 'Enter') {
      const lines = (e.target.value + '\n').split('\n')
      // 如果已经有 4 行，就阻止默认行为
      if (lines.length > MAX_LINES) {
        e.preventDefault()
      }
    }
  }

  /* 2. 兜底：粘贴或 set 值时再截断 */
  function handleInput(val) {
    const truncated = truncateLines(val)
    if (truncated !== val) {
      nextTick(() => {
        form.value.approveReview = truncated
      })
    }
  }

  const route = useRoute();

  import {
    watch
  } from 'vue'

  // 监听 requireId 变化，解决同路由复用问题
  watch(
    () => route.query.requireId || route.params.requireId,
    (newId) => {
      data.queryParams.requireId = newId || null
      handleQuery() // 立即重新查询
    }, {
      immediate: true
    } // 首次进入时也执行一次
  )

  onMounted(() => {
    const id = route.query.requireId || route.params.requireId;
    if (id) {
      data.queryParams.requireId = id;
    }
    getList(); // 发起请求
  });



  getList();
</script>